//
//  ZJSqlit.m
//  XMPPIMDemo
//
//  Created by ZJ on 17/4/7.
//  Copyright © 2017年 ZJ. All rights reserved.
//

#import "ZJSqlit.h"
#import "YYModel.h"
#import "NSObject+additions.h"
@implementation ZJSqlit


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.keyValueStore = [[YTKKeyValueStore alloc]initDBWithName:@"LovingPartyBuilding"];
        [self.keyValueStore createTableWithName:DATATABLE_NAME];
    }
    return self;
}
/** 创建表名 */
- (void)createTableWithName:(NSString *)name{
    [self.keyValueStore createTableWithName:name];
}

- (void)putObject:(id)object withId:(NSString *)objectId intoTable:(NSString *)tableName{
    //对象转字典
    NSArray * addArray = [object yy_modelToJSONObject];
    
    NSString * SqlitString = [self.keyValueStore getStringById:objectId fromTable:tableName];
    if (!SqlitString) {//原数据库不存在
      
        [self.keyValueStore putString:[addArray yy_modelToJSONString] withId:objectId intoTable:tableName];
    }else{//存在
        NSMutableArray *array = [[self jsonStringToObject:SqlitString] mutableCopy];
        //把新加入的放在最前面
        NSArray *newArray = [addArray arrayByAddingObjectsFromArray:array];
        
        [self.keyValueStore putString:[newArray yy_modelToJSONString] withId:objectId intoTable:tableName];
    }
}

- (void)deleteObjectById:(NSString *)objectId fromTable:(NSString *)tableName{
    [self.keyValueStore deleteObjectById:objectId fromTable:tableName];
}

- (void)deleteObjec:(id)object ObjectById:(NSString *)objectId fromTable:(NSString *)tableName{
    NSString * SqlitString = [self.keyValueStore getStringById:objectId fromTable:tableName];
    if (SqlitString) {
        NSMutableArray *array = [[self jsonStringToObject:SqlitString] mutableCopy];
        [array removeObject:[object yy_modelToJSONObject]];
         [self.keyValueStore putString:[array yy_modelToJSONString] withId:objectId intoTable:tableName];
    }
}

- (NSArray *)getStringById:(NSString *)stringId fromTable:(NSString *)tableName{
    
    NSString *string = [self.keyValueStore getStringById:stringId fromTable:tableName];
    NSArray *array = @[];
    if (string) {
        array = [self jsonStringToObject:string];
    }
    return array;
}

@end
